<template>
    <div class="password-form-container">
        <el-dialog :visible.sync="dialogVisible"
                   title="修改密码"
                   custom-class="consult-dialog"
                   :append-to-body='true'
                   width="30%" @close="close">
            <el-form ref="passwordForm"
                     status-icon
                     label-position="left"
                     :rules="passwordRules"
                     :model="passwordForm">
                <el-form-item prop="oldPassword" label="输入原密码：">
                    <el-input
                            style="width: 75%"
                            maxlength="20"
                            autocomplete="off"
                            show-password
                            v-model="passwordForm.oldPassword"
                            placeholder="请输入原始密码"/>
                </el-form-item>

                <el-form-item prop="newPassword" label="输入新密码：">
                    <el-input
                            style="width: 75%"
                            maxlength="20"
                            autocomplete="off"
                            show-password
                            v-model="passwordForm.newPassword"
                            placeholder="请输入新密码"/>
                </el-form-item>

                <el-form-item prop="check" label="确认新密码：">
                    <el-input
                            style="width: 75%"
                            maxlength="20"
                            autocomplete="off"
                            show-password
                            v-model="passwordForm.check"
                            placeholder="请再次输入新密码"/>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="update" class="password-btn" round>确认修改</el-button>
                <el-button @click="close" round>取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
  import {updatePassword} from '@/api/user';
  import {validPassword} from '@/validate/register';
  import {mapActions, mapGetters} from 'vuex';

  export default {
    data(){

      //检验密码
      const validatePassword = (rule, value, callback) => {
        if (!validPassword(value)){
          callback(new Error("请输入正确的密码，密码格式为6-20位的字母与数字组合"));
        }
        else callback()
      }

      //检验确认密码
      const validateCheck = (rule, value, callback) => {
        if (value !== this.passwordForm.newPassword || value.length < 6){
          callback(new Error("两次密码输入不一致，请重新输入"))
        }
        else callback()
      }

      return{
        dialogVisible: false,
        passwordForm:{
          userId: '',
          oldPassword: '',
          newPassword: '',
          check: ''
        },

        passwordRules:{
          oldPassword:[{validator: validatePassword,trigger: 'blur'}],
          newPassword:[{validator: validatePassword,trigger: 'blur'}],
          check:[{validator: validateCheck,trigger: 'blur'}],
        }
      }
    },

    methods: {
      open(){
        this.dialogVisible = true
        this.passwordForm.userId = this.userId
      },

      close(){
        this.$refs.passwordForm.resetFields();
        this.dialogVisible = false
        this.resetForm()
      },

      resetForm () {
        this.passwordForm.userId = ''
        this.passwordForm.oldPassword = ''
        this.passwordForm.newPassword = ''
        this.passwordForm.check = ''
      },

      update(){
        this.$refs.passwordForm.validate((valid) => {
          if (valid) {
            //检验通过，判断新旧密码是否一致
            if (this.passwordForm.newPassword !== this.passwordForm.oldPassword){
              updatePassword(this.userId,this.$qs.stringify(this.passwordForm)).then(result => {
                let {code} = result
                if (code === 20000){
                  this.logout().then(result => {
                    this.$router.push("/")
                    window.location.reload()
                    alert("修改密码成功！请重新登录！")
                  })
                }
                else {
                  // this.$message.error("修改密码失败！原始密码输入错误，请重新输入！");
                  this.$message(
                    {
                      message:'修改密码失败！原始密码输入错误，请重新输入！',
                      type:'error',
                      customClass:'password-message'
                    }
                  );
                }
              })
            }

            else {
              this.$message(
                {
                  message:'新密码和旧密码一致，请重新输入！',
                  type:'error',
                  customClass:'password-message'
                }
              );
              // this.$message.error("新密码和旧密码一致，请重新输入")
              return;
            }

          } else {
            return false;
          }
        });
      },

      ...mapActions('login',{
        'logout': 'logout'
      })
    },

    computed: {
      ...mapGetters({
        'userId': 'id'
      })
    },

  }
</script>

<style scoped>
    .password-btn{
        background-color: #f20d0d;
        color: #FFFFFF;
        border-color: #FFFFFF;
    }
</style>
<style>
    password-message{
        z-index:3000 !important;
    }
</style>
